import os, datetime
from rest_framework import permissions, filters, response, status
from rest_framework.decorators import action
from apps.api.interface.models import InterfaceModel
from apps.api.interface.serializers import InterfaceModelSerializer, RunInterfaceModelSerializer
from apps.basic.environment.models import EnvironmentModel
from apps.api.testcase.models import TestCaseModel
from base.settings import YML_FILE_PATH
from utils import viewsets, common
from utils.response import message_response


class InterfaceViewSet(viewsets.MyViewSets):
    queryset = InterfaceModel.objects.all()
    serializer_class = InterfaceModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    @action(methods=["POST"], detail=True)
    def run(self, request, *args, **kwargs):
        interface_obj = self.get_object()
        super().create(request, *args, **kwargs)
        env = EnvironmentModel.objects.filter(id=request.data["env_id"]).filter(is_delete=0).first()
        stamp_path = os.path.join(YML_FILE_PATH, datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S"))
        os.makedirs(stamp_path)
        cases_obj = TestCaseModel.objects.filter(interface_id=interface_obj.id).filter(is_delete=0)
        if len(cases_obj) == 0:
            message = {"run": "此接口下没有用例，无法运行！"}
            result = message_response(code=1, message=message)
            return response.Response(result, status=status.HTTP_200_OK)
        for case_obj in cases_obj:
            common.assemble_case(stamp_path, env, case_obj)
        return common.run_case(interface_obj.name, stamp_path)

    def get_serializer_class(self):
        if self.action == "run":
            return RunInterfaceModelSerializer
        else:
            return self.serializer_class

    def perform_create(self, serializer):
        if self.action == "run":
            pass
        else:
            serializer.save()
